#include <libcomm.h>

void __SignalHandler(int signo) 
{
	printf("SIGNAL(%d) interrupt !\n",signo);
	printf("%s",StackTracer::TraceStack().c_str());
	exit(0);
}

class MyMessageHandler : public MessageHandler
{
public:
	virtual void OnOpen(){ printf("-->%s(%s)\n",__FUNCTION__,this->Peer()->Address().ToString().get());}
	virtual void OnClose(SocketClient::ConnectionState reason){ printf("-->%s(%s):%d\n",__FUNCTION__,this->Peer()->Address().ToString().get(),reason);}
	virtual void OnMessage(const char* buffer, int size)
	{ 
		printf("-->%s(%p,%d): %s\n",__FUNCTION__,buffer,size,buffer);
		if(strcmp(buffer,"exit") == 0)
		{
			this->Peer()->Close();
		}
		else if(strcmp(buffer,"hello") == 0)
		{
			Thread::Sleep(5000);
		}
	}	
};

int main(int argc, char *argv[])
{
#ifndef COMM_MSVC
	struct sigaction act;
	act.sa_handler = __SignalHandler;
	MYLIB_ASSERT_ERRNO(0==sigfillset(&act.sa_mask));//forbid all signal while handler.
	act.sa_flags = 0;
	//MYLIB_ASSERT_ERRNO(0==sigaction(SIGINT,&act,NULL));
	MYLIB_ASSERT_ERRNO(0==sigaction(SIGSEGV,&act,NULL));
	MYLIB_ASSERT_ERRNO(0==sigaction(SIGILL,&act,NULL));
	MYLIB_ASSERT_ERRNO(0==sigaction(SIGFPE,&act,NULL));
	MYLIB_ASSERT_ERRNO(0==sigaction(SIGTERM,&act,NULL));
	MYLIB_ASSERT_ERRNO(0==sigaction(SIGABRT,&act,NULL));
	//signal(SIGUSR1,SIG_IGN);
#endif

	LOGDEBUG("COMLIB: %s",common_version());

	CommTime now = Timer::Now();
	printf("%04d-%02d-%02d(%d) %02d:%02d:%02d:%06d\n",now.year,now.month,now.day,now.wday,now.hour,now.minute,now.second,now.microsecond);

	//SocketAddress address(40218,"127.0.0.1");
#ifdef __GNUC__
	SocketAddress address(String::format("%s/server.sock",Application::GetApplicationDirectory().get()));
#endif
	String input(512);
	MessageReactor reactor(address,new CommMessageHandlerFactory<MyMessageHandler>(),(argc==1)?false:true,(argc==1)?ThreadPool::DefaultThreadsCount:1);
	do 
	{
		gets(input);
		if(input == "")
		{
			continue;
		}
		if(input == "q")
		{
			break;
		}
		else if(input == "c")
		{
			reactor.Messager()->Peer()->Close();
			//break;
			continue;
		}
		reactor.Messager()->Write(input.get(),input.length()+1);
	} while (true);
	
	return 0;
}